Date Arithmetic

documentation: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#timeseries-offsets

Type Description
date Store calendar date (year, month, day) using a Gregorian Calendar
datetime Store both date and time
timedelta Difference between two datetime values
common date arithmetic operations
  • calculate differences between date
  • generate sequences of dates and time spans
  • convert time series to a particular frequency

Date, time, functions

documentation: http://pandas.pydata.org/pandas-docs/stable/api.html#top-level-dealing-with-datetimelike

to_datetime(*args, **kwargs) Convert argument to datetime.
to_timedelta(*args, **kwargs) Convert argument to timedelta
date_range([start, end, periods, freq, tz, ...]) Return a fixed frequency datetime index, with day (calendar) as the default
bdate_range([start, end, periods, freq, tz, ...]) Return a fixed frequency datetime index, with business day as the default
period_range([start, end, periods, freq, name]) Return a fixed frequency datetime index, with day (calendar) as the default
timedelta_range([start, end, periods, freq, ...]) Return a fixed frequency timedelta index, with day as the default
infer_freq(index[, warn]) Infer the most likely frequency given the input index.

In [3]:
import pandas as pd
import numpy as np
from datetime import datetime
now()

In [4]:
now = datetime.now()
now


Out[4]:
datetime.datetime(2016, 8, 16, 14, 12, 8, 750310)

In [5]:
now.year, now.month, now.day


Out[5]:
(2016, 8, 16)

In [6]:
delta = now - datetime(2001, 1, 1)
delta


Out[6]:
datetime.timedelta(5706, 51128, 750310)

In [7]:
delta.days


Out[7]:
5706

Parsing Timedelta

from string

In [8]:
pd.Timedelta('4 days 7 hours')


Out[8]:
Timedelta('4 days 07:00:00')
named keyword arguments

In [9]:
# note: these MUST be specified as keyword arguments
pd.Timedelta(days=1, seconds=1)


Out[9]:
Timedelta('1 days 00:00:01')
integers with a unit

In [10]:
pd.Timedelta(1, unit='d')


Out[10]:
Timedelta('1 days 00:00:00')
create a range of dates from Timedelta

In [11]:
us_memorial_day = datetime(2016, 5, 30)
print(us_memorial_day)
us_labor_day = datetime(2016, 9, 5)
print(us_labor_day)
us_summer_time = us_labor_day - us_memorial_day
print(us_summer_time)
type(us_summer_time)


2016-05-30 00:00:00
2016-09-05 00:00:00
98 days, 0:00:00
Out[11]:
datetime.timedelta

In [12]:
us_summer_time_range = pd.date_range(us_memorial_day, periods=us_summer_time.days, freq='D')
summer_time time series with random data

In [13]:
us_summer_time_time_series = pd.Series(np.random.randn(us_summer_time.days), index=us_summer_time_range)
us_summer_time_time_series.tail()


Out[13]:
2016-08-31   -0.347080
2016-09-01   -0.266705
2016-09-02    0.337686
2016-09-03   -0.210966
2016-09-04   -1.593387
Freq: D, dtype: float64

In [ ]: